'''
Created on 2022/04/24

@author: shenchh
'''
import sys, os, re
import json
import shutil
tab_space = "      "

def merge_json(json_file, fh_w):

    start_flag = 0
    line_num = 0
    jsonlines = []
    lines = []
    json_line = re.compile(r'.*\n')

    for path, dirs, files in os.walk(json_file):

        for file in files:
            file_path = os.path.join(path, file)
            if file == "cockpit_settings_definition.json":
                with open(file_path, mode = 'r', encoding = 'utf-8', errors = 'ignore', newline = '\n') as fh_r:
                    file_content = fh_r.read() + '\n'
                    # linesカウント
                    for m in re.finditer(json_line, file_content):
                        jsonlines.append(m.group())
            else:
                with open(file_path, mode = 'r', encoding = 'utf-8', errors = 'ignore', newline = '\n') as fh_r:
                    file_content = fh_r.read() + '\n'
                    # linesカウント
                    for m in re.finditer(json_line, file_content):
                        lines.append(m.group())


    for jsonline in jsonlines:

        if "VehicleSettings" in jsonline:
            if start_flag == 0:
                start_flag = 1           
        elif "]" in jsonline:
            start_flag = 0
        else:
            pass
        
        if start_flag == 0:
            fh_w.write(f'{jsonline}')
        elif start_flag == 1:
            start_flag = 2
            for line in lines:
                if "VehicleSettings" in line:
                    line = line.replace("{","")
                    line = line.replace("}","")
                    line = line.replace("\n","")
                    line = line.replace(" ","")
                    line = line.replace(":",": ")
                    line = line.split(",")
                    if line_num == 0:
                        line_num = 1
                        fh_w.write(f'{tab_space}{line[0]},\n')
                        fh_w.write(f'{tab_space}{line[1]},\n')
                        fh_w.write(f'{tab_space}{line[2]},\n')
                        fh_w.write(f'{tab_space}{line[3]}\n')
                        fh_w.write('    }')
                    else:
                        fh_w.write(',\n')
                        fh_w.write('    {\n')
                        fh_w.write(f'{tab_space}{line[0]},\n')
                        fh_w.write(f'{tab_space}{line[1]},\n')
                        fh_w.write(f'{tab_space}{line[2]},\n')
                        fh_w.write(f'{tab_space}{line[3]}\n')
                        fh_w.write('    }')
            fh_w.write(f'\n')
    fh_w.write(f'\n')



def merge_header(head_file, fh_w):

    start_flag = 0
    headlines = []
    lines = []
    head_line = re.compile(r'.*\n')

    for path, dirs, files in os.walk(head_file):

        for file in files:
            
            file_path = os.path.join(path, file)
            if file == "settings_provider_client.h":
                with open(file_path, mode = 'r', encoding = 'utf-8', errors = 'ignore', newline = '\n') as fh_r:
                    file_content = fh_r.read() + '\n'
                    # linesカウント
                    for m in re.finditer(head_line, file_content):
                        headlines.append(m.group())
            else:
                with open(file_path, mode = 'r', encoding = 'utf-8', errors = 'ignore', newline = '\n') as fh_r:
                    file_content = fh_r.read() + '\n'
                    # linesカウント
                    for m in re.finditer(head_line, file_content):
                        lines.append(m.group())


    for headline in headlines:

        if "##########arene start" in headline:
            start_flag = 1
            fh_w.write(f'{headline}\n')
            for line in lines:
                fh_w.write(f'{line}')
            #fh_w.write(f'\n')
        elif "##########arene end" in headline:
            start_flag = 0
        else:
            pass
        
        if start_flag == 0:
            fh_w.write(f'{headline}')
        else:
            pass

    fh_w.write(f'\n')



def merge_capnp(capnp_fpath, fh_w):

    start_flag = 0
    APIlines = []
    lines = []
    capnp_line = re.compile(r'.*\n')

    for path, dirs, files in os.walk(capnp_fpath):

        for file in files:
            file_path = os.path.join(path, file)
            print(file_path)
            if file == "SettingsProviderCockpitAPI.capnp":
                with open(file_path, mode = 'r', encoding = 'utf-8', errors = 'ignore', newline = '\n') as fh_r:
                    file_content = fh_r.read() + '\n'
                    # linesカウント
                    for m in re.finditer(capnp_line, file_content):
                        APIlines.append(m.group())
            else:
                with open(file_path, mode = 'r', encoding = 'utf-8', errors = 'ignore', newline = '\n') as fh_r:
                    file_content = fh_r.read() + '\n'
                    # linesカウント
                    for m in re.finditer(capnp_line, file_content):
                        lines.append(m.group())


    for APIline in APIlines:

        if "##########arene start" in APIline:
            start_flag = 1
            fh_w.write(f'{APIline}\n')
            for line in lines:
                fh_w.write(f'{line}')
            #fh_w.write(f'\n')
        elif "##########arene end" in APIline:
            start_flag = 0
        else:
            pass
        
        if start_flag == 0:
            fh_w.write(f'{APIline}')
        else:
            pass

    fh_w.write(f'\n')



if __name__ == '__main__':
    retry = 0
    while True:
        input_path = input('Please input file path = ').strip()
        capnp_path = input('Please input capnp_path = ').strip()
        json_path = input('Please input json_path = ').strip()
        header_path = input('Please input header_path = ').strip()
        # input_path = './header'
        if retry > 3:
            print(f'error exit.')
            sys.exit(1)
        elif not os.path.exists(input_path):
            retry += 1
            print(f'{input_path} is not exits.')
            continue
        else:
            break


    ##########################
    json_result = "./cockpit_settings_definition.json"
    capnp_result = "./SettingsProviderCockpitAPI.capnp"
    header_result = "./settings_provider_client.h"
    try:
        print (os.getcwd())

        if os.path.isdir(input_path):

            os.chdir(input_path)
            
            capnp_fh_w = open(capnp_result, mode = 'w', encoding = 'utf-8')
            json_fh_w = open(json_result, mode = 'w', encoding = 'utf-8')
            header_fh_w = open(header_result, mode = 'w', encoding = 'utf-8')

            for path, dirs, files in os.walk(input_path):
                print(path)
                
                if path.endswith('capnp'):
                    merge_capnp(path, capnp_fh_w)
                    capnp_fh_w.close()
                elif path.endswith("header"):
                    merge_header(path, header_fh_w)
                    header_fh_w.close()
                elif path.endswith("json"):
                    merge_json(path, json_fh_w)
                    json_fh_w.close()
                else:
                    pass

        else:
            pass

        shutil.copy(json_result, json_path)
        shutil.copy(capnp_result, capnp_path)
        shutil.copy(header_result, header_path)
    except OSError as err:
        print("OS error: {0}".format(err))
    except ValueError:
        print("Could not convert data to an integer.")
    except:
        print("Unexpected error:", sys.exc_info()[0])
        raise

    # check file name

